<?php
/*
 * 本文件包含公用函数。
 * date:2011-1-4
 * author:alex zengjf
 */

require_lib('util/req_util');

//预定义的字符转换为 HTML 实体
function htmlentities_deep($value){
 	if (empty($value)){
        return $value;
    }else{
        return is_array($value) ? array_map('htmlentities_deep', $value) :
        htmlspecialchars($value, ENT_QUOTES, $GLOBALS['context']->get_app_conf('charset'));
    }
}
function getAgeByID($id){
    if(empty($id)) return '';
        $date=strtotime(substr($id,6,8));
    $today=strtotime('today');
    $diff=floor(($today-$date)/86400/365);
    $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
    return $age;
}

function config_item($param) {
	return $GLOBALS['context']->get_app_conf($param) ? $GLOBALS['context']->get_app_conf($param) : '';
}
function curl_post_url($url){
	require_lib('net/Snoopy.class');

	/*
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, $url);
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
	$file_content = curl_exec($curl_handle);
	*/
	$snoopy = new Snoopy();
	$snoopy->submit($url, null);
	if($snoopy->error){
		$file_content = $snoopy->error;
	}else{
		$file_content = $snoopy->results;
	}
	return $file_content;
}
function  set_html_url($params,$str){
    if(is_array($params)) {
        foreach($params as $k=>$v){
            $str .= '-'.(!empty($v) ? $v : 0);
        }
    }
    return $str.'.html';
}

function get_static_url($url, $position, $replace, $last='',$replace_str ='-') {
    $url_arr = explode($replace_str, $url);
    if(isset($url_arr["{$position}"])) {
        $url_arr["{$position}"] = $replace;
    }
    $result = implode($replace_str, $url_arr).$last;
    return get_domain().'/'.$result;
}

/**
 * 分等级获得分类信息
 * @param $data
 * @param $cat_path
 * @param $cat_id
 * @return array
 */
function get_cat_level($data, $cat_path, $cat_id) {
    $cat_arr = explode(',', trim($cat_path, ','));
    if($cat_path == ',') {
        $res = $data["{$cat_id}"];
    }else {
        $res = get_eval_str($cat_arr, $data, $cat_id);
    }
    return isset($res) ? $res : array();
}

/**
 * 执行的cat分类
 * @param $arr
 * @param $data
 * @param $cat_id
 * @return array
 */
function get_eval_str($arr, $data, $cat_id) {
    $str = "\$res=\$data";
    $i = count($arr);
    foreach($arr as $k=>$v) {
        if($i == $k+1) {
            $str .="[$v]['sub_cats'][$cat_id];";
        }else {
            $str .="[$v]['sub_cats']";
        }

    }
    eval($str);
    return isset($res) ? $res : array();
}
//获取图片服务器
function get_img_server(){
	$img_server = $GLOBALS['context']->get_app_conf('img_server');
	if (!is_array($img_server)) {
		return $img_server;
	} else {
		$count = count($img_server)-1;
		$select = rand(0, $count);
		return $img_server["{$select}"];
	}
}
//生成图片路径、格式
function image_url($r_path,$width='',$height=''){
	if($r_path == ''){
		return '/no_pic.png';
	}
	if(empty($r_path)) return '';
	if($width == '' && $height == '') {
		return $r_path;
	}elseif ($width == '' || $height == ''){
		$temp = $width == ''? ("--h_".$height):("--w_".$width);
	}else{
		$temp = "--w_".$width."_h_".$height;
	}
	//后缀
	$arrPath=pathinfo($r_path);
	$file_name = str_replace(".".$arrPath['extension'],$temp.".".$arrPath['extension'], $r_path);
	return $file_name;
}

function get_redirect_url($url,$leval=1){
	$flg = true;
	//$url = str_replace('do_index','',$url);
	switch($leval){
		case 1:
			preg_match_all('/(\w+=(\w\/?)+)(#\w+)?/i', $url, $links);
			if (!empty($links)) {
				$links = $links[0];
				$path = array_shift($links);$path = substr($path, stripos($path, '=')+1);
				$value = array_shift($links);$key = substr($value, 0, stripos($value, '='));
				$value = substr($value, stripos($value, '=')+1);
				switch($path) {
					case 'goods/':				           //详情
						$count = 1;
						$color = '';
						if (config_item('show_goods_by_color') && !empty($links)) {
							$color = array_shift($links);
							$color = '_' . str_replace('=', '-', $color, $count);
						}
						$url = "/goods-{$value}{$color}.html";
						break;
					case 'list_goods/':				       //列表
						$url = '/list';
						if ($value) {
							$url .= '-'.$value.'.html';
						}
						break;
					case 'list_goods/search': 	           //搜索
						$url = '/search';
						if ($value) {
							$url .= '-'.$value;
						}
						/*
						$url .= '.html';
						if ($key != '') {
							$links[] = "{$key}={$value}";
						}
						if ($key != 'key_search') {
							$links[] = "key_search=";
						}
						*/
						break;
					case 'list_goods/brand':    	       //品牌
						$url = '/brand-'.$value.'.html';
						break;
					case 'list_goods/series':		       //系列
						$url = '/series-'.$value.'.html';
						break;
					case 'promos/spike':			       //秒杀
						$url = '/spike-'.$value.'.html';
						break;
					case 'promos/team':			           //团购
						$url = '/team-'.$value.'.html';
						break;
					case 'points/':				           //积分换购
						$url = '/point-'.$value.'.html';
						break;
					case 'help/':				           //帮助
						$url = '/help-'.$value.'.html';
						break;
					default:
						$flg = false;
						break;
				}
				if (!empty($links) && $flg) {
					$params = '';
					foreach ($links as $r) {
						$params .= "{$r}&";
					}
					$url .= '?' . trim($params, '&');
				}
			}
			break;
		default:
			$flg = false;
			break;
	}
	if ($flg === false) {
		$url = str_replace('/?app_act=', '/', $url);
		$pos = strpos($url, '&');
		if($pos !== false){
			$url = substr_replace($url, '?', $pos, 1);
		}
	}
	return $url;
}

function get_domain(){
        /* 协议 */
        $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';

        /* 域名或IP地址 */
        if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
        {
            $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
        }
        elseif (isset($_SERVER['HTTP_HOST']))
        {
            $host = $_SERVER['HTTP_HOST'];
        }
        else
        {
            /* 端口 */
            if (isset($_SERVER['SERVER_PORT']))
            {
                $port = ':' . $_SERVER['SERVER_PORT'];

                if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
                {
                    $port = '';
                }
            }
            else
            {
                $port = '';
            }

            if (isset($_SERVER['SERVER_NAME']))
            {
                $host = $_SERVER['SERVER_NAME'] . $port;
            }
            elseif (isset($_SERVER['SERVER_ADDR']))
            {
                $host = $_SERVER['SERVER_ADDR'] . $port;
            }
        }
        return $protocol . $host;
}

function get_curr_url($excluded='',$type='string',$reverse=true){
	$url = '';
	$arrUrl = array();
	foreach($GLOBALS['context']->request as $k=>$v){
		if(!isset($_GET[$k])){
			continue;
		}
		if($k == 'key_search'){
			$v = get_encodeing_word($v);
			if($GLOBALS['context']->get_app_conf('search_type')=='php') $v = rawurlencode(base64_encode($v));
		}
		if($reverse){
			if(is_array($excluded)){
				if(in_array($k,$excluded) || $v == ''){
					continue;
				}
			}else{
				if(stristr($k,$excluded) !== false || $v == ''){
					continue;
				}
			}
		}else{
			if(is_array($excluded)){
				if(!in_array($k,$excluded) || $v == ''){
					continue;
				}
			}
		}

		if($type == 'string'){
			$url .= "&$k=$v";
		}else{
			$arrUrl[$k]=$v;
		}
	}

	if($type == 'string'){
		$url = rtrim($url, '&');
		return $url;
	}else{
		return $arrUrl;
	}
}

/**
+----------------------------------------------------------
*  全角转半角
+----------------------------------------------------------
* @param string  $
* @param integer $
+----------------------------------------------------------
*/
function make_semiangle($str){
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
                 'ｙ' => 'y', 'ｚ' => 'z',
                 '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
                 '】' => ']', '〖' => '[', '〗' => ']', '“' => '"', '”' => '"',
                 '‘' => '\'', '’' => '\'', '｛' => '{', '｝' => '}', '《' => '<',
                 '》' => '>',
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-',
                 '：' => ':', '。' => '.', '、' => '\\', '，' => ',',
                 '；' => ';', '？' => '?', '！' => '!', '……' => '^', '‖' => '|',
                 '｜' => '|', '〃' => '"', '·'=>'`','～'=>'~',
                 '　' => ' ','＄'=>'$','＠'=>'@','＃'=>'#','＾'=>'^','＆'=>'&','＊'=>'*',
                 '＂'=>'"');

    return strtr($str, $arr);
}

function get_encodeing_word($word){
	$charset = $GLOBALS['context']->get_app_conf('charset');
	$flg = mb_check_encoding($word, $charset);
	if(isset($_SERVER['HTTP_ACCEPT_CHARSET'])){
		$uchar = explode(';',$_SERVER['HTTP_ACCEPT_CHARSET']);
		$in_charset = $uchar[0];
	}else{
		$charsets = $GLOBALS['context']->get_app_conf('charsets');
		if(!$charsets){
			$in_charset = mb_detect_encoding($word, 'GBK, GB2312');
		}else{
			$in_charset = mb_detect_encoding($word, $charsets);
		}
	}
	if(!$flg){
		$word = mb_convert_encoding($word, $charset, $in_charset);
	}

	return $word;
}

function get_days ($curyear, $curmon, $currentDay) {
	 $max_mday=31;
		if(in_array($curmon,array(2,4,6,9,11))){
			if($curmon==2){
				if($curyear % 400==0 || ($curyear % 4==0 && $curyear % 100!=0)) $max_mday=29;
				else $max_mday=28;
			}
			else $max_mday=30;
		}
		$option ='';
		for($i=1;$i<=$max_mday; $i++) {
			if($currentDay == $i) $option .="<option value='".$i."' selected='selected'>$currentDay</option>";
			elseif($currentDay==0 && $i ==1) $option .="<option value='".$i."' selected='selected'>$i</option>";
			else $option .="<option value='".$i."'>$i</option>";
		}
	return $option;
}

function get_session_id(){
	$GLOBALS['context']->init_session();
	return session_id();
}

function sql_into($data,$table,$cmd=0){
	$keys=$vals="";
	while(list($k,$v)=each($data)){
		$keys.=$k.",";
		$vals.="'".$v."',";
	}
	if($keys&&$vals){
		$keys=substr($keys,0,-1);
		$vals=substr($vals,0,-1);
	}
	$sql="INSERT INTO ".$table." ($keys) VALUES($vals)";

	if($cmd>0){
		return $sql;
	}else{
		$result=$GLOBALS['context']->db->query($sql);
		$fp=$GLOBALS['context']->db->insert_id();
		return $fp;
	}
}

function sql_into_2($data,$table,$cmd=0){
	$keys=$vals="";
	while(list($k,$v)=each($data)){
		$keys.=$k.",";
		$vals.="'".$v."',";
	}
	if($keys&&$vals){
		$keys=substr($keys,0,-1);
		$vals=substr($vals,0,-1);
	}
	$sql="INSERT INTO ".$table." ($keys) VALUES($vals)";
	if($cmd>0){
		return $sql;
	}else{
		try {
			$GLOBALS['context']->db->query($sql);
			return true;
		} catch(Exception $e) {
			return false;
		}
	}
}

function sql_update($data,$table,$key,$val,$cmd=0){
	$keys="";
	while(list($k,$v)=each($data)){
		$keys.=$k."='".$v."',";
	}
	if($keys){
		$keys=substr($keys,0,-1);
	}
	$sql="UPDATE ".$table." SET ".$keys." WHERE ".$key."='".$val."'";
	if($cmd>0){
		return $sql;
	}else{
		try {
			$GLOBALS['context']->db->query($sql);
			return true;
		} catch(Exception $e) {
			return false;
		}
	}
}

function sql_update_add($data,$table,$key,$val,$cmd=0){
	$keys="";
	while(list($k,$v)=each($data)){
		$v = floatval($v);
		$keys.="$k=$k+$v,";
	}
	if($keys){
		$keys=substr($keys,0,-1);
	}
	$sql="UPDATE ".$table." SET ".$keys." WHERE ".$key."='".$val."'";
	if($cmd>0){
		return $sql;
	}else{
		try {
			$GLOBALS['context']->db->query($sql);
			return true;
		} catch(Exception $e) {
			return false;
		}
	}
}

function sql_transaction($sqls){
	//sql回滚
	//sqls格式: sql1;sql2;sql3......
	$status = array();
	$arr=explode(";",$sqls);
	$GLOBALS['context']->db->begin_trans();
	try{
		while(list($k,$v)=each($arr)){
			$GLOBALS['context']->db->query($v);
		}
		$status  = 1;
		$GLOBALS['context']->db->commit();
	}catch(Exception $e){
		$GLOBALS['context']->db->rollback();
		$status  = 0;
	}
	return $status;
}

/**
 * 检查文件类型
 *
 * @access      public
 * @param       string      filename            文件名
 * @param       string      realname            真实文件名
 * @param       string      limit_ext_types     允许的文件类型
 * @return      string
 */
function check_file_type($filename, $realname = '', $limit_ext_types = '') {
    if ($realname) {
        $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
    } else {
        $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false) {
        return '';
    }

    $str = $format = '';

    $file = @fopen($filename, 'rb');
    if ($file) {
        $str = @fread($file, 0x400); // 读取前 1024 个字节
        @fclose($file);
    } else {
        if (stristr($filename, ROOT_PATH) === false) {
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
                    $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
                    $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
                    $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert') {
                $format = $extname;
            }
        } else {
            return '';
        }
    }

    if ($format == '' && strlen($str) >= 2) {
        if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') {
            $format = 'mid';
        } elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') {
            $format = 'wav';
        } elseif (substr($str, 0, 3) == "\xFF\xD8\xFF") {
            $format = 'jpg';
        } elseif (substr($str, 0, 4) == 'GIF8' && $extname != 'txt') {
            $format = 'gif';
        } elseif (substr($str, 0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
            $format = 'png';
        } elseif (substr($str, 0, 2) == 'BM' && $extname != 'txt') {
            $format = 'bmp';
        } elseif ((substr($str, 0, 3) == 'CWS' || substr($str, 0, 3) == 'FWS') && $extname != 'txt') {
            $format = 'swf';
        } elseif (substr($str, 0, 4) == "\xD0\xCF\x11\xE0") {   // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str, 0x200, 4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') {
                $format = 'doc';
            } elseif (substr($str, 0x200, 2) == "\x09\x08" || $extname == 'xls') {
                $format = 'xls';
            } elseif (substr($str, 0x200, 4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') {
                $format = 'ppt';
            }
        } elseif (substr($str, 0, 4) == "PK\x03\x04") {
            $format = 'zip';
        } elseif (substr($str, 0, 4) == 'Rar!' && $extname != 'txt') {
            $format = 'rar';
        } elseif (substr($str, 0, 4) == "\x25PDF") {
            $format = 'pdf';
        } elseif (substr($str, 0, 3) == "\x30\x82\x0A") {
            $format = 'cert';
        } elseif (substr($str, 0, 4) == 'ITSF' && $extname != 'txt') {
            $format = 'chm';
        } elseif (substr($str, 0, 4) == "\x2ERMF") {
            $format = 'rm';
        } elseif ($extname == 'sql') {
            $format = 'sql';
        } elseif ($extname == 'txt') {
            $format = 'txt';
        }
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) {
        $format = '';
    }

    return $format;
}

function private_logs($word) {
	$fp = fopen(ROOT_PATH.$GLOBALS['context']->app['name'].'/logs/'.date('Y-m-d').'.log',"a");
	flock($fp, LOCK_EX) ;
	fwrite($fp, '['.date('H:i:s')."] {$word}\r\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}
/*生成随机数*/
function random ( $length, $numberonly= false ) {
    $hash = '';
    if ( $numberonly ) {
        $chars = '0123456789';
    } else {
        $chars = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    }
    $max = strlen ( $chars ) - 1;
    mt_srand ( ( double ) microtime() * 1000000 );
    for ( $i = 0; $i < $length; $i ++  ) {
        $hash .= $chars[mt_rand ( 0, $max )];
    }
    return $hash;
}

